package com.example.springvue.controller.admin;

import com.example.springvue.common.annotation.LogAnnotation;
import com.example.springvue.common.annotation.PassToken;
import com.example.springvue.common.handler.NotExistException;
import com.example.springvue.common.jwt.Md5Utils;
import com.example.springvue.common.returnthrow.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CommonController {

    //获取yaml中配置的上传路径属性
    @Value(("${file.imagesRealPath}"))
    private String uploadPath;
    @Value("${file.imagesServerPath}")
    private String serverPath;

    /**
     * 管理员列表
     *
     * @return
     */
    @LogAnnotation
    @ResponseBody
    @PassToken
    @PostMapping(value = "/admin/upload")
    public Result<Map< String, Object >> Upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws NotExistException {
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");

        StringBuffer url = request.getRequestURL();

        //域名
        String domainName = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();

        //图片后缀
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //拼接图片名称
        String name = Md5Utils.getMd5Code(file.getOriginalFilename()+dateFormat.format(date))+type;
        //拼接保存图片的真实地址
        String saveUri=uploadPath+""+dateFormat.format(date)+"/"+name;
        //拼接访问图片的地址
        String urls =domainName+serverPath+dateFormat.format(date)+"/"+name;
//        log.info("图片原文件名={} 图片访问地址={} 图片保存真实地址={}",fileName,visibleUri,saveUri);

        String image =serverPath+dateFormat.format(date)+"/"+name;


        File saveFile = new File(saveUri);
        //判断是否存在文件夹，不存在就创建，但其实可以直接手动确定创建好，这样不用每次保存都检测
        if (!saveFile.exists()){
            saveFile.mkdirs();
        }
        Map<String,Object> map =new HashMap<>();
        map.put("url",urls);
        map.put("image",image);
        try{
            file.transferTo(saveFile);  //保存文件到真实存储路径下
        }
        catch (NotExistException | IOException e)
        {
            throw new NotExistException(e.getMessage());
        }
        return Result.success("请求成功",map);

    }
}
